package com.xiaolei.openokjoke.Fragments

import android.content.Intent
import android.graphics.Color
import android.os.Message
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.umeng.analytics.MobclickAgent
import com.xiaolei.easyfreamwork.utils.Log
import com.xiaolei.openokjoke.Activitys.ImageViewActivity
import com.xiaolei.openokjoke.Adapters.JokeAdapter
import com.xiaolei.openokjoke.Adapters.RecyclerBaseAdapter
import com.xiaolei.openokjoke.Base.BaseV4Fragment
import com.xiaolei.openokjoke.Beans.JokeBean
import com.xiaolei.openokjoke.Configs.EventAction
import com.xiaolei.openokjoke.Exts.enqueue
import com.xiaolei.openokjoke.Net.APPNet
import com.xiaolei.openokjoke.Net.BaseRetrofit
import com.xiaolei.openokjoke.R
import kotlinx.android.synthetic.main.fragment_randomjoke.*
import java.util.*

/**
 * 随机笑话
 * Created by xiaolei on 2018/3/8.
 */
class RandomFragment : BaseV4Fragment() {
    private var mPageIndex = 1
    private var isLoading = false
    private val appnet by lazy {
        BaseRetrofit.create(APPNet::class.java)
    }
    private val list = LinkedList<JokeBean>()
    private val adapter by lazy {
        JokeAdapter(list, activity)
    }

    override fun contentViewId(): Int = R.layout.fragment_randomjoke

    override fun initObj() {
        Log.d("initObj", "initObj")
    }

    override fun initView() {
        refresh_layout.setColorSchemeColors(Color.parseColor("#ecc96a"))
        refresh_layout.setOnRefreshListener {
            loadServerData()
        }
    }

    override fun initData() {

        Log.d("initData", "initData")
    }

    override fun setListener() {
        recycleview.layoutManager = LinearLayoutManager(activity).apply {
            orientation = LinearLayoutManager.VERTICAL
        }
        recycleview.adapter = adapter
        adapter.setOnItemClickListener(object : RecyclerBaseAdapter.OnItemClickListener {
            override fun onItemClick(viewHolder: RecyclerView.ViewHolder) {
                val position = viewHolder.adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    startActivity(Intent(activity, ImageViewActivity::class.java).apply {
                        putExtra("url", list[position].content)
                    })
                }
                adapter!!.setOnLoadMoreListener(object : RecyclerBaseAdapter.OnLoadMoreListener {
                    override fun loadMore() {
                        if (!isLoading) {
                            mPageIndex++
                            loadServerData()
                        }
                    }
                })
            }
        })
    }

    override fun loadData() {
        loadServerData(true)
    }

    // 真正网络数据
    fun loadServerData(cache: Boolean = false) {
        context?.let {
            val call = if (cache) {
                appnet.cacheRandomJoke()
            } else {
                appnet.randomJoke(mPageIndex)
            }
            call.enqueue(it,
                    // onSuccess:
                    { result ->
                        result.appdata?.let {
                            println(it)
                            if (mPageIndex == 1) {
                                // 第一页需要清空数据再加入
                                adapter!!.clear()
                            }
                            adapter!!.addAll(it.model);
                            //list.addAll(it.model)
                        }
                    },
                    // onFinaly:
                    {
                        adapter.notifyDataSetChanged()
                        refresh_layout.isRefreshing = false
                        MobclickAgent.onEvent(activity, "refresh_random")
                    },
                    // onFail:
                    {
                        println("onFail")
                    }
            )
        }
    }

    override fun onEvent(msg: Message) {
        if (msg.what == EventAction.refreshSuiji) {
            val layoutManager = recycleview.layoutManager as LinearLayoutManager
            val firstPosition = layoutManager.findFirstVisibleItemPosition()
            if (firstPosition == 0) // 显示第一个
            {
                refresh_layout.isRefreshing = true
                loadServerData(false)
            } else // 滚回最顶部
            {
                recycleview.smoothScrollToPosition(0)
            }
        }
    }

}